﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Medianamik.Core.DAL.SQL
{
    public class OrderByClause : ISqlQueryPart 
    {
        private List<KeyValuePair<Column, string>> _columns;
        public OrderByClause()
        {
            _columns = new List<KeyValuePair<Column, string>>() ;
        }

        public OrderByClause OrderBy(Column pColumn)
        {
            _columns.Add(new KeyValuePair<Column, string>(pColumn, "ASC"));
            return this;
        }

        public OrderByClause OrderByDesc(Column pColumn)
        {
            _columns.Add(new KeyValuePair<Column, string>(pColumn, "DESC"));
            return this;
        }

        public StringBuilder ToSQL()
        {
            if(_columns.Count == 0)
            {
                return new StringBuilder();
            }

            var orderBy = new StringBuilder(" ORDER BY ");
            var firstColumn = _columns.First();
            orderBy.Append(firstColumn.Key.NameWithAlias)
                .Append(" " + firstColumn.Value);
            foreach (var c in Enumerable.Skip(_columns, 1))
            {
                orderBy.Append("," + c.Key.NameWithAlias)
                    .Append(" " + c.Value );
            }
            return orderBy;
        }
    }
}
